package com.googlecode.gwtbb.client.only.widget.form.entry;

import com.google.gwt.user.client.ui.Widget;
import com.googlecode.gwtbb.client.only.widget.basic.MultiPictureFileUpload;
import com.googlecode.gwtbb.client.only.widget.basic.PictureFileUpload;
import com.googlecode.gwtbb.client.shared.util.StringUtils;
import com.googlecode.gwtbb.client.shared.validation.Failure;
import com.googlecode.gwtbb.client.shared.validation.FieldId;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jan 6, 2009
 */
public class LabeledMultiPictureFileUploadFormEntry extends LabeledFormEntry {
	private MultiPictureFileUpload entryMultiPictureFileUpload;

	public LabeledMultiPictureFileUploadFormEntry(FieldId fieldId, String labelText, int labelRow, int labelCol, MultiPictureFileUpload entryMultiPictureFileUpload) {
		// fileUploads cannot have their value set for security reasons... so defaultValue is inapplicable
		super(fieldId, null, labelRow, labelCol, labelText);
		this.entryMultiPictureFileUpload = entryMultiPictureFileUpload;
	}

	public MultiPictureFileUpload getEntryMultiPictureFileUpload() {
		return entryMultiPictureFileUpload;
	}

	public Widget getEntryWidget() {
		return entryMultiPictureFileUpload;
	}

	public String getValue() {
		StringBuffer value = new StringBuffer();
		for (PictureFileUpload pfu : entryMultiPictureFileUpload.getPictureFileUploads()) {
			if (pfu.getStatus() == PictureFileUpload.STATUS_UPLOADED) {
				if (value.length() > 0)
					value.append(",");
				value.append(pfu.getServerFileName());
			}
		}
		return value.length() > 0 ? value.toString() : null;
	}

	public void redisplayFailures() {
		clearFailures();
		for (PictureFileUpload pfu : entryMultiPictureFileUpload.getPictureFileUploads()) {
			String errorMsg = pfu.getErrorMsg();
			if (StringUtils.isNotEmpty(errorMsg))
				addFailure(new Failure(errorMsg));
		}
	}

	public void setValue(String value) {
		// fileUploads cannot have their value set for security reasons...
		// any attempt to set the value will be interpreted as resetting the form
		entryMultiPictureFileUpload.reset();
	}
}
